package com.itheima.tliaswebmanagement.filter;

import com.itheima.tliaswebmanagement.controller.CurrentHolder;
import com.itheima.tliaswebmanagement.controller.JwtUtils;


import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.获取请求路径
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURL().toString();

        //2.判断请求路径是否为 登录 ，如果是放行，否则继续往下执行
        if (url.contains("login")) {
            log.info("当前为登录操作，放行");
            filterChain.doFilter(request,response);//放行代码
            return;
        }

        //3.获取请求头中的token
        //"token"是登录接口的请求头名称（自己命名的）
        String jwt = request.getHeader("token");

        //4.判断token是否存在，如果不存在则返回401状态码
        if (!StringUtils.hasLength(jwt)) {
            log.info("token不存在，返回401");
            response.setStatus(401);
            return;
        }

        //5.如果token存在，则解析，若解析失败则返回401状态码
        try {
            Claims claims = JwtUtils.parseJWT(jwt);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(401);
            return;
        }

        //6.放行
        log.info("token有效，放行");
        filterChain.doFilter(request,response);

        //7.清空当前线程绑定的id
        CurrentHolder.remove();
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
